//
//  webService.m
//  DuMydemo
//
//  Created by glandale on 13-1-4.
//  Copyright (c) 2013年 __MyCompanyName__. All rights reserved.
//

#import "webService.h"
#import "webConfig.h"
#import "AppDelegate.h"
#import "SVProgressHUD.h"
@implementation webService
@synthesize webData = _webData;
@synthesize methodName = _methodName;
/*
 //Mark: 生成SOAP1.1版本的ASIHttp请求
 参数 webURL：                远程WebService的地址，不含*.asmx
 参数 webServiceFile：        远程WebService的访问文件名，如service.asmx
 参数 xmlNS：                    远程WebService的命名空间
 参数 webServiceName：        远程WebService的名称 方法名
 参数 wsParameters：            调用参数数组，形式为[参数1名称，参数1值，参数2名称，参数2值⋯⋯]，如果没有调用参数，此参数为nil
 */


-(void)commonGetSharedRequest:(NSString *)methodName wsparas:(NSMutableArray *)wsparas{
    
    
    //获取当前IP
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSString *currentIp = myDelegate.currentIp;
    //2、生成调用参数
    NSString * soapParas = @"";
    //url字符串拼接
    NSString *urlStr;
    if (wsparas!=Nil)
    {
        int i = 0;
        for (i = 0; i < [wsparas count];  i=i+2)
        {
            
            soapParas = [soapParas stringByAppendingFormat:@"%@=%@&",
                         [wsparas objectAtIndex:i],
                         [wsparas objectAtIndex:i+1]];
            
        }
        NSString *para=[soapParas substringToIndex:[soapParas length]-1];
        urlStr= [NSString stringWithFormat:@"http://%@%@%@.aspx?%@",currentIp,WEBSFILE,methodName,para];
    }else{
        urlStr = [NSString stringWithFormat:@"http://%@%@%@.aspx",currentIp,WEBSFILE,methodName];
    }
    urlStr = [urlStr stringByReplacingOccurrencesOfString:@" " withString:@"\040"];
    if (![methodName isEqualToString:LOGIN]) {
        urlStr= [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
   
    NSURL *url = [NSURL URLWithString:urlStr];
  
    
 
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];//超时限制
    //请求
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	//NSLog(@"=====url=%@",url);
	//如果连接已经建好，则初始化data
	if( theConnection )
	{
		
        _webData = [NSMutableData alloc];
        //NSLog(@"theConnection is!");
	}
	else
	{
		//NSLog(@"theConnection is NULL");
	}
    
}
-(void)commonPostSharedRequest:(NSString *)methodName psotDic:(NSDictionary *)postDic{
    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSString *currentIp = myDelegate.currentIp;

    NSString *urlString = [NSString stringWithFormat:@"http://%@%@%@.aspx",currentIp,WEBSFILE,methodName];
    
    //static NSString *urlString = @"http://www.google.cn";
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    
    NSError *error = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDic options:NSJSONWritingPrettyPrinted error:&error];
    
//    NSString *httpBodyString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSString *httpBodyString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSLog(@"postDATA===%@",httpBodyString);
    
    //[request setHTTPBody:[httpBodyString dataUsingEncoding:NSUTF8StringEncoding]];
    
    //post = [[NSString alloc] initWithFormat:@"message=%@",@"hello,world."];
    
    
    
    
    NSData *postData = [httpBodyString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    
    [request setHTTPBody:postData];
    
    [request setHTTPMethod:@"POST"];
    
    NSURLResponse *reponse;
    
//    NSError *error = nil;
    
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&reponse error:&error];
    
    if (error) {
        
        NSLog(@"Something wrong: %@",[error description]);
        
    }else {
        
        if (responseData) {
            
            NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
            [[NSNotificationCenter defaultCenter] postNotificationName:methodName object:responseData];

            //NSLog(@"get %@",responseString);
            
        }
        
    }
    
    
    
    
}

-(void)picAndRecordPostSharedRequest:(NSString *)methodName postData:(NSData *)postDataXingCan
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSString *currentIp = myDelegate.currentIp;
    NSString *urlString = [NSString stringWithFormat:@"http://%@%@%@.aspx",currentIp,WEBSFILE,methodName];
    
    NSLog(@"%@",urlString);
    
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *serverURL = [NSURL URLWithString:urlString];
    
    //将图片数据转化成 NSInputStream
    NSInputStream *inputStreamForFile = [NSInputStream inputStreamWithData:postDataXingCan];
    
    //上传大小
    NSNumber *contentLength = (NSNumber *)[NSNumber numberWithInteger:[postDataXingCan length]];
    
    //开始拼数据
    NSMutableURLRequest *request;
    request = [NSMutableURLRequest requestWithURL:serverURL];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBodyStream:inputStreamForFile];
    [request setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[contentLength description] forHTTPHeaderField:@"Content-Length"];
    
    // 请求
    // self.aSynConnection = [NSURLConnection connectionWithRequest:request delegate:self];
    NSURLResponse *urlResponse;
    NSData *returnData=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
    NSString *result = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    [[NSNotificationCenter defaultCenter] postNotificationName:methodName object:returnData];
    //NSLog(@"rrrrr=%@",result);
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //NSLog(@"connection: didReceiveResponse:1");
	[_webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[_webData appendData:data];
	//NSLog(@"connection: didReceiveData:2");
    
}

//如果电脑没有连接网络，则出现此信息（不是网络服务器不通）
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //NSLog(@"ERROR with theConenction");
    [SVProgressHUD dismiss];
	[connection cancel];
	
}

//http连接的回调方法
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	//NSLog(@"3 DONE. Received Bytes: %d", [_webData length]);
    
    NSString *theJson = [[NSString alloc] initWithBytes: [_webData mutableBytes] length:[_webData length] encoding:NSUTF8StringEncoding];
    //NSLog(@"TheXMl == %@",theJson);
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:_methodName object:_webData];
    _webData=Nil;
}


+(void)webtext:(NSString *)test{
    
    NSError *error;
    
   NSString *jsonStr = @"{\"error_code\":0,\"error_msg\":\"xxxxxx\",\"count\":2,\"results\":[{\"jobSheetId\":\"20130502\",\"plateNumber\":\"粤Axxx\",\"vin\":\"1234\",\"importantNotice\":\"xxxx\",\"carTypeId\":\"GD1\",\"year\":\"2013\",\"custormerName\":\"张三\", \"evaluatorName\":\"李四\",\"stateName\":\"估价\"},{\"jobSheetId\":\"2013020411\",\"plateNumber\":\"粤Axxx\",\"vin\":\"5432\",\"importantNotice\":\"xxxx\",\"carTypeId\":\"GD1\",\"year\":\"2013\",\"custormerName\":\"张三\",\"evaluatorName\":\"李四\",\"stateName\":\"预约\"}]}";
    
    NSData *jsData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *jsnary = [NSJSONSerialization JSONObjectWithData:jsData options:NSJSONReadingMutableLeaves error:&error];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:test object:jsnary];
    
}
+(void)repairBtn:(NSString*)test{
    
    NSLog(@"webservice jinru++++++");
    NSError *error;
    
    NSString *jsonStr = @"{\"error_code\":0,\"error_msg\":\"xxxxxx\",\"count\":2,\"results\":[{\"jobSheetId\":\"20130502\",\"milemeter\":\"5556\",\"comingDate\":\"2013-02-03\", \"deliveryDate\":\"2013-02-03\"},{\"jobSheetId\":\"20130502\",\"milemeter\":\"5556\",\"comingDate\":\"2013-02-03\", \"deliveryDate\":\"2013-02-03\"}]}";
    
    NSData *jsData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *jsnary = [NSJSONSerialization JSONObjectWithData:jsData options:NSJSONReadingMutableLeaves error:&error];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:test object:jsnary];
    
}
@end
